<script setup>
	import {
		ref,
		nextTick,
		computed
	} from 'vue'

	import {
		onShow
	} from '@dcloudio/uni-app'
	import VideoPlayer from './src/video.vue'

	//播放器ref
	const videoPlayer = ref(null)

	//当前播放
	const currentVideo = ref({
		number: null,
		title: null,
		src: null,
		duration: 0,
		played_time: 0,
		playStatus: 'wait', // wait:待播放 | play:播放中 | paus:暂停 | end:播放结束
	})

	const episodesList = ref([])

	// 视频切换状态管理
	const isSwitching = ref(false)
	let switchTimeout = null

	onShow(() => {
		getEpisodesList()
	})

	// 计算属性：获取播放状态文本
	const getPlayStatusText = (item) => {
		if (currentVideo.value.number !== item.number || currentVideo.value.playStatus === 'wait') {
			return '待播放';
		}
		switch (currentVideo.value.playStatus) {
			case 'play':
				return '暂停';
			case 'paus':
				return '继续';
			case 'end':
				return '重新播放';
			default:
				return '待播放';
		}
	}

	// 计算属性：获取播放状态样式类
	const getPlayStatusClass = (item) => {
		if (currentVideo.value.number !== item.number) {
			return 'status-waiting';
		}
		switch (currentVideo.value.playStatus) {
			case 'play':
				return 'status-playing';
			case 'paus':
				return 'status-paused';
			case 'end':
				return 'status-ended';
			default:
				return 'status-waiting';
		}
	}

	// 保存当前视频进度
	const saveCurrentProgress = () => {
		if (currentVideo.value.number && currentVideo.value.played_time > 0) {
			const current = episodesList.value.find(item => item.number === currentVideo.value.number)
			if (current) {
				current.played_time = currentVideo.value.played_time
				current.progress = (current.played_time / current.duration) * 100
				console.log('保存进度:', current.number, current.played_time)
			}
		}
	}

	// 加载视频历史进度
	const loadVideoProgress = (videoNumber) => {
		const episode = episodesList.value.find(item => item.number === videoNumber)
		return episode ? episode.played_time : 0
	}

	// 视频准备就绪回调
	const handleVideoReady = () => {
		console.log('视频准备就绪:', currentVideo.value.number)
	}

	// 处理视频状态变化（来自视频控件）
	const handleStatusChange = (status) => {
		console.log('视频状态变化:', status)
		if (currentVideo.value.number) {
			currentVideo.value.playStatus = status
			console.log('更新播放状态:', currentVideo.value.number, status)
		}
	}

	//播放/暂停(选集)
	const handlePlayMedia = async (index) => {
		// 防止快速连续切换
		if (isSwitching.value) {
			console.log('正在切换中，请稍候...')
			return
		}

		const current = episodesList.value[index];
		console.log("选择视频:", current);

		// 如果点击的是当前正在播放的视频
		if (currentVideo.value.number === current.number) {
			// 处理同一视频的播放/暂停/重新播放逻辑
			if (currentVideo.value.playStatus === 'play') {
				// 正在播放，暂停
				console.log('暂停播放:', current.title)
				currentVideo.value.playStatus = 'paus'
				videoPlayer.value?.pause()
			} else if (currentVideo.value.playStatus === 'paus') {
				// 暂停状态，继续播放
				console.log('继续播放:', current.title)
				currentVideo.value.playStatus = 'play'
				await videoPlayer.value?.play()
			} else if (currentVideo.value.playStatus === 'end') {
				// 强制重置所有进度
				currentVideo.value.played_time = 0
				current.played_time = 0
				current.progress = 0
				currentVideo.value.playStatus = 'play'

				// 重新播放 - 先seek到0，再播放
				await nextTick()

				// 先seek到开始位置
				console.log('seek到0')
				await videoPlayer.value?.seek(0)

				// 等待seek完成后再播放
				setTimeout(async () => {
					console.log('开始重新播放')
					await videoPlayer.value?.play()
				}, 300) // 增加延迟时间
			}
		} else {
			// 切换到新视频
			isSwitching.value = true

			// 保存当前视频进度
			saveCurrentProgress();

			// 清除之前的切换操作
			if (switchTimeout) {
				clearTimeout(switchTimeout)
			}

			// 切换到新视频（强制刷新对象引用）
			const newVideo = {
				number: current.number,
				title: current.title,
				src: current.src,
				duration: current.duration,
				played_time: 0, // 先重置为0，避免状态污染
				playStatus: 'play',
			};

			console.log('切换到新视频:', newVideo)
			currentVideo.value = {
				...newVideo
			};

			// 等待DOM更新
			await nextTick();

			// 延迟加载历史进度，确保视频已切换
			switchTimeout = setTimeout(async () => {
				const historyProgress = loadVideoProgress(current.number)
				if (historyProgress > 0) {
					currentVideo.value.played_time = historyProgress
					current.played_time = historyProgress
					current.progress = (historyProgress / current.duration) * 100

					// 设置播放位置
					await videoPlayer.value?.seek(historyProgress)
				}

				// 开始播放
				await videoPlayer.value?.play()

				// 重置切换状态
				setTimeout(() => {
					isSwitching.value = false
				}, 500)
			}, 300)
		}
	}

	//更新时间
	const handleTimeUpdate = ({
		currentTime,
		progress
	}) => {
		// 只有当当前播放的视频编号匹配且正在播放时才更新进度
		if (currentVideo.value.playStatus === 'play' && currentTime > 0 && !isSwitching.value) {
			const current = episodesList.value.find(item => item.number === currentVideo.value.number);
			if (current) {
				current.played_time = currentTime;
				current.progress = progress;
				// 同步更新currentVideo的进度
				currentVideo.value.played_time = currentTime;
				console.log('更新进度:', current.number, currentTime, progress)
			}
		}
	}

	const handleVideoEnd = () => {

		currentVideo.value.playStatus = 'end';
		// 保存最终进度
		saveCurrentProgress()
	}


	// 智能格式（自动选择是否显示小时）
	const formatTimeSmart = (seconds) => {
		if (!seconds || isNaN(seconds)) return '00:00'
		const hours = Math.floor(seconds / 3600)
		const minutes = Math.floor((seconds % 3600) / 60)
		const remainingSeconds = Math.floor(seconds % 60)

		if (hours > 0) {
			return `${hours}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
		} else {
			return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
		}
	}

	//模拟从后台获取数据
	const getEpisodesList = () => {
		//后台返回的数据
		const res_data = [{
				number: 1,
				title: 'uniApp官方视频',
				src: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4',
				duration: 121,
				played_time: 0,
			},
			{
				number: 2,
				title: '动漫',
				src: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
				duration: 52,
				played_time: 0,
			},
			{
				number: 3,
				title: '姜子牙',
				src: 'https://vod.pipi.cn/43903a81vodtransgzp1251246104/bbd4f07a5285890808066187974/v.f42906.mp4',
				duration: 124,
				played_time: 0,
			}
		]
		const res = res_data.map((item) => {
			const progress = (item.played_time / item.duration) * 100;
			return {
				...item,
				progress,
			}
		})
		episodesList.value = res;
	}
</script>

<template>
	<VideoPlayer ref="videoPlayer" :media-src="currentVideo.src" :initial-time="currentVideo.played_time"
		:number="currentVideo.number" @update:time="handleTimeUpdate" @ended="handleVideoEnd" @ready="handleVideoReady"
		@status-change="handleStatusChange" />
	<view class="content">
		<view class="media-list" v-for="(item,index) in episodesList" :key="index" :style="{
			      background: `linear-gradient(90deg, #79FF79 ${item.progress}%, #e8f5e8 ${item.progress}%)`
			    }">
			<view class="media-info">
				<view>
					<text class="media-number">{{ item.number }}.</text>
					<text class="media-title">{{ item.title }}</text>
				</view>
				<view class="media-time">
					{{ formatTimeSmart(item.played_time) }} / {{ formatTimeSmart(item.duration) }}
				</view>
			</view>
			<view class="play-button" @click="handlePlayMedia(index)" @tap="handlePlayMedia(index)">
				<text :class="getPlayStatusClass(item)">
					{{ getPlayStatusText(item) }}
				</text>
			</view>
		</view>
	</view>
</template>



<style lang="scss">
	.content {
		margin: 24rpx;

		.media-list {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 8rpx;
			margin: 12rpx 0;
			border-radius: 12rpx;

			&:last-child {
				border-bottom: none;
			}

			.media-info {
				flex: 1;
				display: grid;
				align-items: center;

				.media-number {
					color: #666;
					font-size: 28rpx;
					margin-right: 10rpx;
				}

				.media-title {
					color: #333;
					font-size: 30rpx;
					font-weight: 500;
				}

				.media-time {
					padding-left: 40rpx;
					color: #6c757d;
					font-size: 28rpx;
				}
			}

			.play-button {
				padding: 16rpx 24rpx;
				border-radius: 8rpx;
				background-color: #f8f9fa;
				border: 1rpx solid #e9ecef;
				cursor: pointer;
				transition: all 0.3s ease;

				&:active {
					transform: scale(0.95);
				}

				text {
					font-size: 26rpx;

					&.status-waiting {
						color: #6c757d;
					}

					&.status-playing {
						color: #28a745;
						font-weight: 500;
					}

					&.status-paused {
						color: #ffc107;
						font-weight: 500;
					}

					&.status-ended {
						color: #dc3545;
						font-weight: 500;
					}
				}
			}
		}
	}
</style>